#include "serial.h"
#include "http.h"
#include "speech.h"

#include <QDebug>
#include <QHostInfo>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QMap>
#include <qfile.h>

Speech::Speech(QObject *parent) : QObject(parent)
{
    m_baiduTokenUrl = QString("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=%1&client_secret=%2&");
    m_clientId = QString("AY8k8wwRUK13bafAA8v3LAjK");
    m_clientSecret = QString("LqQ8M0X55nzlc8xhEzVGrizBnG49gNyd");
}

QString Speech::speechIndetify(QString filename)
{
    // 获取access_token
    QString tokenUrl = QString(m_baiduTokenUrl).arg(m_clientId).arg(m_clientSecret);

    QMap<QString, QString>  head;
    head.insert(QString("Content-Type"), QString("audio/pcm;rate=16000"));
    QByteArray requestData;
    QByteArray replyDate;
    Http http;
    bool result = http.post_sync(tokenUrl, head, requestData, replyDate);

    if (result) {
        QString key = "access_token";
        QString accessToken = getJsonValue(replyDate, key);
        QString baiduUrl = "http://vop.baidu.com/server_api?dev_pid=1537&cuid=%1&token=%2";
        QString speechUrl = QString(baiduUrl).arg(QHostInfo::localHostName()).arg(accessToken);
        // 把文件转换成QByteArray
        QFile file;
        file.setFileName(filename);
        file.open(QIODevice::ReadOnly);
        requestData = file.readAll();
        file.close();

        // 再次发起请求
        bool result = http.post_sync(speechUrl, head, requestData, replyDate);
        if (result) {
            QString key = "result";
            QString text = getJsonValue(replyDate, key);
            return text;
        }

    } else {
        return nullptr;
    }
    return nullptr;
}

QString Speech::getJsonValue(QByteArray replyData, QString key)
{
    QJsonParseError parseError;
    QJsonDocument jsonDocument = QJsonDocument::fromJson(replyData, &parseError);
    if (parseError.error == QJsonParseError::NoError) {
        if (jsonDocument.isObject()) {
            // 获取json对象
            QJsonObject jsonObject = jsonDocument.object();
            if (jsonObject.contains(key)) {
                QJsonValue jsonval = jsonObject.value(key);
                if (jsonval.isString()) {
                    return jsonval.toString();
                } else if (jsonval.isArray()) {
                    QJsonArray arr = jsonval.toArray();
                    QJsonValue jv = arr.at(0);
                    return jv.toString();
                }
             }
        }
    }
    return nullptr;
}
